﻿using System.Net.Sockets;
using System.Net;
using System.Text;

namespace P2P客户端
{
    internal class Program
    {
        private static UdpClient client;
        private static IPEndPoint remoteEP;
        private static bool hasReceivedPeerAddress = false; // 是否收到对方地址标志

        static void Main(string[] args)
        {
            client = new UdpClient();
            IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse("192.168.176.127"), 9999);

            // 向服务器发送连接请求
            string message = "CONNECT_REQUEST";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(message);
            client.Send(sendBuffer, sendBuffer.Length, serverEndpoint);

            // 启动监听线程
            Thread listenerThread = new Thread(ListenForMessages);
            listenerThread.Start();

            // 等待接收对方的地址信息，然后开始P2P通信
            Console.WriteLine("等待接收对方地址信息...");
            while (!hasReceivedPeerAddress)
            {               
                Thread.Sleep(1000); // 等待接收
            }
            // 启动P2P通信
            P2PCommunication();
        }

        static void ListenForMessages()
        {
             remoteEP = new IPEndPoint(IPAddress.Any, 0);

            while (true)
            {
                byte[] receiveBuffer = client.Receive(ref remoteEP);
                string message = Encoding.UTF8.GetString(receiveBuffer);
                Console.WriteLine($"Received from {remoteEP}: {message}");

                // 如果接收到的是ADDRESS_INFO信息
                if (message.StartsWith("ADDRESS_INFO:") && !hasReceivedPeerAddress)
                {
                    // 解析对方的IP和端口
                    string[] parts = message.Split(':');
                    string targetIp = parts[1];
                    int targetPort = int.Parse(parts[2]);

                    // 设置目标地址为对方的地址
                    remoteEP = new IPEndPoint(IPAddress.Parse(targetIp), targetPort);
                }
                else
                {
                    // 处理接收到的其他P2P消息
                    Console.WriteLine(message);
                }
            }
        }

        static void P2PCommunication()
        {
            while (true)
            {
                // 从控制台输入消息
                string message = Console.ReadLine();
                byte[] sendBuffer = Encoding.UTF8.GetBytes(message);

                // 发送数据到对方
                client.Send(sendBuffer, sendBuffer.Length, remoteEP);
                Console.WriteLine($"发送消息到 {remoteEP.Address}:{remoteEP.Port}: {message}");
            }
        }
    }
}
